package com.example.fy.coolweather.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * Created by fy on 2016/5/11.
 */
public class Utility {
    private static final String TAG = "Utility";

    /**
     * 解析和处理服务器返回的json数据,并将解析出的数据存储到本地数据库
     */
    public static void handleWeatherResponse(Context context,String resopnse){
        try{
            JSONObject jsonObject = new JSONObject(resopnse);
            JSONObject weatherInfo = jsonObject.getJSONObject("retData");
            String cityName = weatherInfo.getString("city");
            String weatherCode = weatherInfo.getString("citycode");
            String temp1 = weatherInfo.getString("l_tmp");
            String temp2 = weatherInfo.getString("h_tmp");
            String weatherDesp = weatherInfo.getString("weather");
            String publishTime = weatherInfo.getString("time");
            Log.d(TAG, "handleWeatherResponse: "+System.currentTimeMillis());

            saveWeatherInfo(context,cityName,weatherCode,temp1,temp2,weatherDesp,publishTime);

        }catch (JSONException e){
            Log.d(TAG, "handleWeatherResponse: 写入sharepreference失败");
            e.printStackTrace();
        }
    }

    private static void saveWeatherInfo(Context context, String cityName, String weatherCode,
                                        String temp1, String temp2, String weatherDesp, String publishTime) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日", Locale.CHINA);
        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
        editor.putBoolean("city_selected",true);
        editor.putString("city_name",cityName);
        editor.putString("weather_code",weatherCode);
        editor.putString("temp1",temp1);
        editor.putString("temp2",temp2);
        editor.putString("weather_desp",weatherDesp);
        editor.putString("publish_time",publishTime);
        editor.putString("current_date",sdf.format(new Date()));
        editor.commit();
    }
}
